
var menuItemArray = [];
var sensors_js = 0;

function functionName(func)
{
    var retval = "";
    if(func)
    {
        var funcNameLong=func.toString();
        var funcNameShort = funcNameLong.replace("function", "");
        var endIndex = funcNameShort.indexOf("(");
        retval = funcNameShort.substr(0, endIndex);
    }
    return retval;
}

function MenuItem(label, id)
{
    this.label = label;
    this.id = id;
    this.onSelect = 0;
    this.append = function(menuItem) {
        var handlerFunction = functionName(menuItem.onSelect);
        wrt.appendMenuItem(menuItem.label, menuItem.id, this.id, handlerFunction);
        menuItemArray.push(menuItem);
    };
    this.remove = function(menuItem) {
        if(menuItem) {
            wrt.remove(menuItem.id);
            for (var i = 0; i < menuItemArray.length; i++) {
                if(menuItemArray[i] && menuItemArray[i].id == id) {
                    menuItemArray[i] = 0;
                    break;
                }
            }
        }
    };
    this.setDimmed = function(flag) {
        wrt.setDimmed(this.id, flag);
    };
}


function Menu()
{
	this.append = function (menuItem)
	{
            var handlerFunction = functionName(menuItem.onSelect);
            wrt.appendMenuItem(menuItem.label, menuItem.id, 0, handlerFunction);
            menuItemArray.push(menuItem);
	};
	
	this.remove = function (menuItem) {
            menuItem.remove(menuItem);
	};
	
	this.getMenuItemById = function (id) {
            var menuItem;
            var retval = 0;
            for (var i = 0; i < menuItemArray.length; i++) {
                menuItem = menuItemArray[i];
                if(menuItem && menuItem.id == id) {
                    retval = menuItem;
                    break;
                }
            }
            // if menu item not found, create a dymmy menu item
            if(!retval) {
                retval = new MenuItem("", -1);
            }

            return retval;
	};
	
	this.getMenuItemByName = function (menuItemLabel) {
            var menuItem;
            var retval = 0;
            for (var i = 0; i < menuItemArray.length; i++) {
                menuItem = menuItemArray[i];
                if(menuItem && menuItem.label == menuItemLabel) {
                    retval = menuItem;
                    break;
                }
            }
            // if menu item not found, create a dymmy menu item
            if(!retval) {
                retval = new MenuItem("", -1);
            }

            return retval;
        };
	
        this.setLeftSoftkeyLabel = function (label, callbackfunc) {
            wrt.setLeftSoftkeyLabel(label, functionName(callbackfunc));
	};
	
	this.setRightSoftkeyLabel = function (label, callbackfunc) {
            wrt.setRightSoftkeyLabel(label, functionName(callbackfunc));
	};
	
	this.showSoftkeys = function () {
            wrt.showSoftkeys();
	};
	
	this.hideSoftkeys = function () {
            wrt.hideSoftkeys();
	};
	
	this.clear = function () {
            wrt.clear();
	};

	this.onShow = function () {
	};
}


function menuOnShow()
{
   menu.onShow();
}

function Widget()
{
    this.openURL = function(url) {
        wrt.openURL(url);
    };

    this.setPreferenceForKey = function (preference, key) {
        wrt.setPreferenceForKey(preference, key);
    };

    this.preferenceForKey = function (key) {
        return wrt.preferenceForKey(key);
    };

    this.prepareForTransition = function (transitionMode) {
    };

    this.performTransition = function () {
    };

    this.setNavigationEnabled = function (navigationMode) {
       wrt. setNavigationEnabled(navigationMode);
    };

    this.setNavigationType = function (type) {
        wrt.setNavigationType(type);
    };

    this.openApplication = function(uid, param) {
        wrt.openApplication(uid, param);
    };

    this.setDisplayLandscape = function() {
        wrt.setDisplayLandscape();
    };

    this.setDisplayPortrait = function() {
        wrt.setDisplayPortrait();
    };

    var identifier;
    var onshow;
    var onhide;
    var isrotationsupported;
}

function createLocationResult(so)
{
	result = new Object();
	result.ErrorCode = 0;
	result.ErrorMessage = "";
	
	retVal = new Object();
	retVal.Longitude = so.longitude();
	retVal.Latitude = so.latitude();
	retVal.Altitude = so.altitude();
	retVal.SatelliteNumView = 0;
	retVal.SatelliteNumViewUsed = 0;
	retVal.HorizontalSpeed = 0;
	retVal.HorizontalSpeedError = 0;
	retVal.TrueCourse = 0;
	retVal.TrueCourseError = 0;
	retVal.MagneticHeading = 0;
	retVal.MagneticHeadingError = 0;
	retVal.Heading = 0;
	retVal.HeadingError = 0;
	retVal.MagneticCourse = 0;
	retVal.MagneticCourseError = 0;
	
	result.ReturnValue = retVal;
	
	return result;
}

var locationCallbackMethod;
function ILocationImpl()
{
	var locationPlugin = wrt.getPlugin("locationapi");
	
	
	this.GetLocation = function(criteria, callback)
	{
		//criteria.LocationInformationClass
		//criteria.Updateoptions
		//criteria.Updateoptions.UpdateInterval
		//criteria.Updateoptions.UpdateTimeOut
		//criteria.Updateoptions.UpdateMaxAge
		//criteria.Updateoptions.PartialUpdates
		
		resultObj = createLocationResult(locationPlugin);
	
		if(callback)
		{
			locationCallbackMethod = callback;
			//locationPlugin.positionUpdated.connect(this.positionUpdated);
			callback(1,2,resultObj);
		}
		
		return resultObj;
	};
	
	this.Trace = function()
	{
	};
	
	this.Calculate = function()
	{
	};
	
	this.CancelNotification = function()
	{
	};

	this.positionUpdated = function()
	{
		resultObj = createLocationResult(locationPlugin);
		locationCallbackMethod(1,2,resultObj);
	};
}

function ISensorImpl()
{
	var sensorsPlugin = wrt.getPlugin("sensorsapi");
	var sensorchannelsinfoarray = [];
	var transactionIdsAndCallbackFunctions = [];

	this.AddChannelInfo = function(ChannelId, ContextType, Quantity, ChannelType, Location, VendorId, DataItemSize, ChannelDataTypeId)
	{
		var sensorchannelinformation = {
		ChannelId: ChannelId,
		ContextType: ContextType,
		Quantity: Quantity,
		ChannelType: ChannelType,
		Location: Location,
		VendorId: VendorId,
		DataItemSize: DataItemSize,
		ChannelDataTypeId: ChannelDataTypeId
		};		

		sensorchannelsinfoarray.push(sensorchannelinformation);
	};
	
	
	this.AaccelerometerAxisDataEvent = function(TransId, EventCode, DataType, TimeStamp, XAxisData, YAxisData, ZAxisData)
	{
		for (var i = 0; i < transactionIdsAndCallbackFunctions.length; i++) {
			if(transactionIdsAndCallbackFunctions[i] && transactionIdsAndCallbackFunctions[i].TransactionID == TransId) {
				var callbackReturnValue = {
					DataType: DataType,
					TimeStamp: TimeStamp,
					XAxisData: XAxisData,
					YAxisData: YAxisData,
					ZAxisData: ZAxisData
				};
				var result = {
				ReturnValue: callbackReturnValue,
				ErrorCode: 0,
				ErrorMessage: 0
				};
				transactionIdsAndCallbackFunctions[i].CallbackFunction(TransId, EventCode, result);
				break;
			}
		}
	};
	
	this.OrientationDataEvent = function(TransId, EventCode, DataType, TimeStamp, DeviceOrientation)
	{
		for (var i = 0; i < transactionIdsAndCallbackFunctions.length; i++) {
			if(transactionIdsAndCallbackFunctions[i] && transactionIdsAndCallbackFunctions[i].TransactionID == TransId) {
				var callbackReturnValue = {
					DataType: DataType,
					TimeStamp: TimeStamp,
					DeviceOrientation: DeviceOrientation
				};
				var result = {
				ReturnValue: callbackReturnValue,
				ErrorCode: 0,
				ErrorMessage: 0
				};
				transactionIdsAndCallbackFunctions[i].CallbackFunction(TransId, EventCode, result);
				break;
			}
		}
	};

	this.AccelerometerDoubleTappingDataEvent = function(TransId, EventCode, DataType, TimeStamp, DeviceDirection)
	{
		for (var i = 0; i < transactionIdsAndCallbackFunctions.length; i++) {
			if(transactionIdsAndCallbackFunctions[i] && transactionIdsAndCallbackFunctions[i].TransactionID == TransId) {
				var callbackReturnValue = {
					DataType: DataType,
					TimeStamp: TimeStamp,
					DeviceDirection: DeviceDirection
				};
				var result = {
				ReturnValue: callbackReturnValue,
				ErrorCode: 0,
				ErrorMessage: 0
				};
				transactionIdsAndCallbackFunctions[i].CallbackFunction(TransId, EventCode, result);
				break;
			}
		}
	};
	
	this.FindSensorChannel = function(criteria)
	{
		while(sensorchannelsinfoarray.length > 0)
		{
			sensorchannelsinfoarray.pop();
		}
		
		sensorsPlugin.findSensorChannel(criteria.SearchCriterion);

		var result = {
		ReturnValue: sensorchannelsinfoarray,
		ErrorCode: 0,
		ErrorMessage: 0
		};

		return result;
	};
 
	this.RegisterForNotification = function(criteria, callback)
	{
		var retval = sensorsPlugin.registerForNotification(criteria.ListeningType, criteria.ChannelInfoMap.ChannelId, criteria.ChannelInfoMap.ContextType, criteria.ChannelInfoMap.Quantity, criteria.ChannelInfoMap.ChannelType, criteria.ChannelInfoMap.Location, criteria.ChannelInfoMap.VendorId, criteria.ChannelInfoMap.DataItemSize, criteria.ChannelInfoMap.ChannelDataTypeId);
		
		var trIdsAndCallbacks = {
		TransactionID: retval,
		CallbackFunction: callback
		};
		
		transactionIdsAndCallbackFunctions.push(trIdsAndCallbacks);
		
		var result = {
		TransactionID: retval,
		ErrorCode: 0,
		ErrorMessage: 0
		};
		
		return result;
		
	};
	
	this.Cancel = function(criteria)
	{		
		for (var i = 0; i < transactionIdsAndCallbackFunctions.length; i++) {
			if(transactionIdsAndCallbackFunctions[i] && transactionIdsAndCallbackFunctions[i].TransactionID == criteria.TransactionID) {
				transactionIdsAndCallbackFunctions[i] = 0;
				sensorsPlugin.cancel(criteria.TransactionID);
				break;
			}
                }

		var result = {
		ErrorCode: 0,
		ErrorMessage: 0
		};

		return result;
	};

	this.GetChannelProperty = function(criteria)
	{
		var result = {
		PropertyId: "",
		PropertyDataType: 0,
		ItemIndex: 0,
		ReadOnly:false,
		PropertyValue: 0,
		ErrorCode: 0,
		ErrorMessage: ""
		};
	};
}


function Device()
{
	this.getServiceObject = function(provider, interface)
	{
		if(provider=="Service.Location" && interface=="ILocation")
		{
			so = new Object();
			so.ILocation = new ILocationImpl();
			return so;
		}
		else if(provider=="Service.Sensor" && interface=="ISensor")
		{
			so = new Object();
			so.ISensor = new ISensorImpl();
			sensors_js = so.ISensor;
			return so;
		}
	}
}

function addChannelInfo(ChannelId, ContextType, Quantity, ChannelType, Location, VendorId, DataItemSize, ChannelDataTypeId)
{
	sensors_js.AddChannelInfo(ChannelId, ContextType, Quantity, ChannelType, Location, VendorId, DataItemSize, ChannelDataTypeId);
}

function accelerometerAxisDataEvent(TransId, EventCode, DataType, TimeStamp, XAxisData, YAxisData, ZAxisData)
{
	sensors_js.AaccelerometerAxisDataEvent(TransId, EventCode, DataType, TimeStamp, XAxisData, YAxisData, ZAxisData);
}

function accelerometerDoubleTappingDataEvent(TransId, EventCode, DataType, TimeStamp, DeviceDirection)
{
	sensors_js.AccelerometerDoubleTappingDataEvent(TransId, EventCode, DataType, TimeStamp, DeviceDirection);
}

function orientationDataEvent(TransId, EventCode, DataType, TimeStamp, DeviceOrientation)
{
	sensors_js.OrientationDataEvent(TransId, EventCode, DataType, TimeStamp, DeviceOrientation);
}

function widgetOnShow()
{
   widget.onshow();
}

function widgetOnHide()
{
   widget.onhide();
}


var menu = new Menu();
var widget = new Widget();
var device = new Device();
widget.isrotationsupported = wrt.rotationSupported();
